package com.study.compose.beta.activity.coroutines

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import com.module.compose.base.ComposeActivity
import com.module.compose.base.composable.CommonItem
import com.module.compose.base.composable.CommonPage
import com.module.compose.base.composable.swipToRefresh.ComposePullToRefresh
import com.module.compose.base.utils.ScreenBg
import com.module.compose.base.viewModel.PageState
import com.study.compose.beta.R

class BlogHistoryActivity : ComposeActivity<BlogHistoryViewModel>() {

    //数据初始化
    override fun initData() = viewModel.getBlogHistory(intent.getStringExtra("id")!!)

    /**
     * 覆写内容填充方法
     */
    @Composable
    override fun ContentView() {
        //使用此方法获取context
        //val context = LocalContext.current as BaseActivity
        //当多个compose组合的时候，在其他关联的组件中，使用下面的方法获取viewModel
        //var myViewModel: BlogHistoryViewModel = viewModel()

        //把数据转换为状态
        val blogHistory by viewModel.blogHistory.observeAsState()

        //页面状态,把页面分为了四种状态：LOADING, SUC, EMPTY, ERR
        val pageState by viewModel.pageState.observeAsState(PageState.LOADING)

        //刷新状态
        val refreshState by viewModel.refreshState.observeAsState(false)

        CommonPage(title = "文章列表", pageState = pageState) {

            //下拉刷新
            ComposePullToRefresh(
                isRefreshing = refreshState,
                onRefresh = {
                    //请求数据
                    viewModel.getBlogHistory(isRefresh = true, blogId = "409")
                },
            ) {
                //列表
                LazyColumn {
                    items(blogHistory!!.datas) { item ->
                        CommonItem(
                            content = item.title,
                            iconId = R.mipmap.icon_android,
                            showArrow = false,
                            backgroundColor = ScreenBg
                        ) {
                            val uri = Uri.parse(item.link)
                            val intent = Intent(Intent.ACTION_VIEW, uri)
                            startActivity(intent)
                        }
                    }
                }
            }
        }
    }
}